import 'package:dio/dio.dart';
import 'package:flutterdome/config/app_config.dart';
import 'dart:developer';

/// 认证拦截器 - 添加认证相关的请求头
class AuthInterceptor extends Interceptor {
  @override
  void onRequest(
      RequestOptions options,
      RequestInterceptorHandler handler,
      ) {
    // 这里可以添加token等认证信息
    // 示例：从存储中获取token并添加到请求头
    // final token = await StorageService().getToken();
    // if (token != null) {
    //   options.headers['Authorization'] = 'Bearer $token';
    // }

    // 添加通用请求头
    options.headers.addAll({
      'Accept': 'application/json',
      'X-Environment': AppConfig.environment,
      'X-App-Version': '1.0.0',
    });

    super.onRequest(options, handler);
  }
}

/// 日志拦截器 - 打印请求和响应信息
class LogInterceptor extends Interceptor {
  @override
  void onRequest(
      RequestOptions options,
      RequestInterceptorHandler handler,
      ) {
    if (AppConfig.isDebugMode) {
      log('🚀 REQUEST:');
      log('  Method: ${options.method}');
      log('  URL: ${options.baseUrl}${options.path}');
      log('  Headers: ${options.headers}');
      if (options.queryParameters.isNotEmpty) {
        log('  Query Parameters: ${options.queryParameters}');
      }
      if (options.data != null) {
        log('  Body: ${options.data}');
      }
    }
    super.onRequest(options, handler);
  }

  @override
  void onResponse(
      Response response,
      ResponseInterceptorHandler handler,
      ) {
    if (AppConfig.isDebugMode) {
      log('✅ RESPONSE:');
      log('  URL: ${response.requestOptions.baseUrl}${response.requestOptions.path}');
      log('  Status Code: ${response.statusCode}');
      log('  Data: ${response.data}');
    }
    super.onResponse(response, handler);
  }

  @override
  void onError(
      DioException err,
      ErrorInterceptorHandler handler,
      ) {
    if (AppConfig.isDebugMode) {
      log('❌ ERROR:');
      log('  URL: ${err.requestOptions.baseUrl}${err.requestOptions.path}');
      log('  Error: ${err.error}');
      log('  Message: ${err.message}');
      if (err.response != null) {
        log('  Status Code: ${err.response?.statusCode}');
        log('  Response Data: ${err.response?.data}');
      }
    }
    super.onError(err, handler);
  }
}

/// 错误拦截器 - 处理各种网络错误
class ErrorInterceptor extends Interceptor {
  @override
  void onError(
      DioException err,
      ErrorInterceptorHandler handler,
      ) {
    // 处理不同类型的错误
    switch (err.type) {
      case DioExceptionType.connectionTimeout:
      case DioExceptionType.receiveTimeout:
      case DioExceptionType.sendTimeout:
        // 超时错误
        handler.reject(
          NetworkError('网络超时，请检查您的网络连接', err),
        );
        break;
      case DioExceptionType.connectionError:
        // 连接错误
        handler.reject(
          NetworkError('无法连接到服务器，请检查您的网络连接', err),
        );
        break;
      case DioExceptionType.cancel:
        // 请求取消
        handler.reject(
          NetworkError('请求已取消', err),
        );
        break;
      case DioExceptionType.badResponse:
        // 服务器返回错误状态码
        _handleBadResponse(err, handler);
        break;
      case DioExceptionType.unknown:
      default:
        // 其他错误
        handler.reject(
          NetworkError('网络请求失败，请稍后重试', err),
        );
        break;
    }
  }

  void _handleBadResponse(DioException err, ErrorInterceptorHandler handler) {
    final statusCode = err.response?.statusCode;

    switch (statusCode) {
      case 401:
        // 未授权，可能需要重新登录
        handler.reject(
          NetworkError('登录已过期，请重新登录', err, statusCode: 401),
        );
        // 这里可以添加清除token并跳转到登录页面的逻辑
        break;
      case 403:
        // 禁止访问
        handler.reject(
          NetworkError('您没有权限访问此资源', err, statusCode: 403),
        );
        break;
      case 404:
        // 资源不存在
        handler.reject(
          NetworkError('请求的资源不存在', err, statusCode: 404),
        );
        break;
      case 500:
      case 502:
      case 503:
      case 504:
        // 服务器错误
        handler.reject(
          NetworkError('服务器内部错误，请稍后重试', err, statusCode: statusCode),
        );
        break;
      default:
        // 其他状态码
        handler.reject(
          NetworkError(
              '请求失败，状态码：$statusCode', err, statusCode: statusCode),
        );
        break;
    }
  }
}

/// 自定义网络错误类
class NetworkError extends DioException {
  final int? statusCode;
  final String customMessage;

  NetworkError(
    this.customMessage,
    DioException originalError,
    {this.statusCode}
  ) : super(
      requestOptions: originalError.requestOptions,
      response: originalError.response,
      type: originalError.type,
      error: originalError.error,
      message: customMessage
    );

  @override
  String toString() {
    return customMessage;
  }
}